C#(cSharp) Javascript jQuery PHP 

Shuffle Array and array of object values in javascript, PHP

#1 Javascript: in javascript, there is no array shuffle inbuilt function, so we need to find some custom solution
solution1:

var arrData= [
    { some: 1 },
    { some: 2 },
    { some: 3 },
    { some: 4 },
    { some: 5 },
    { some: 6 },
    { some: 7 },
  ];
  console.log(arrData.sort( () => Math.random() - 0.5) );

Solution 2:

function shufflearray(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

#2 PHP: In php array shuffle is very easy to implement because, there is a inbuilt function provided “shuffle()

$arrData= [{ some: 1 },{ some: 2 },{ some: 3 },{ some: 4 },{ some: 5 },{ some: 6 },{ some: 7 }];
print_r(shuffle($arrData)); //this is used just to print output.

#3 C# : In c# there is no direct shuffle function, so we need to use random and orderby to get the output

Random rnd=new Random();
string[] arrData = [{ some: 1 },{ some: 2 },{ some: 3 },{ some: 4 },{ some: 5 },{ some: 6 },{ some: 7 }];
string[] MyRandomArray = arrData.OrderBy(x => rnd.Next()).ToArray();

#4 Java : Implemented via custom function

package com.journaldev.examples;

import java.util.Arrays;
import java.util.Random;

public class ShuffleArray {

	public static void main(String[] args) {
		
		int[] array = { 1, 2, 3, 4, 5, 6, 7 };
		
		Random rand = new Random();
		
		for (int i = 0; i < array.length; i++) {
			int randomIndexToSwap = rand.nextInt(array.length);
			int temp = array[randomIndexToSwap];
			array[randomIndexToSwap] = array[i];
			array[i] = temp;
		}
		System.out.println(Arrays.toString(array));
	}
}
Also Read:  How to enable domain to send mail through PHP mail() script in CPanel

Related posts